package com.tobby.camel.camelinaction.chapter3.order;

import javax.jms.ConnectionFactory;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.jms.JmsComponent;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.CamelSpringTestSupport;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class PurchaseOrderJAXBTest extends CamelSpringTestSupport {

	@Override
	protected AbstractApplicationContext createApplicationContext() {
		return new ClassPathXmlApplicationContext(
				"com/tobby/camel/camelinaction/chapter3/order/order-jaxb.xml");
	}

	@Override
	protected RouteBuilder createRouteBuilder() {
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
				"vm://localhost");
		context.addComponent("jms",
				JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));
		return new RouteBuilder() {

			@Override
			public void configure() throws Exception {
				// Object to xml can omit the contextPath
				from("direct:javaOrder").marshal().jaxb().to("jms:javaOrderQueue");
				// Xml to Object must specify the contextPath, because camel doesn't know
				// how the xml type
				from("jms:javaOrderQueue").unmarshal()
						.jaxb("com.tobby.camel.camelinaction.chapter3.order")
						.to("mock:javaResult");
			}
		};
	}

	@Test
	public void testJaxb() throws InterruptedException {
		MockEndpoint endpoint = getMockEndpoint("mock:order");
		endpoint.expectedMessageCount(1);
		endpoint.message(0).body().isInstanceOf(PurchaseOrder.class);

		PurchaseOrder order = new PurchaseOrder();
		order.setName("Camel in action");
		order.setPrice(4995);
		order.setAmount(1);

		template.sendBody("direct:order", order);
		assertMockEndpointsSatisfied();
	}

	@Test
	public void testJaxbJavaDSL() throws InterruptedException {
		MockEndpoint endpoint = getMockEndpoint("mock:javaResult");
		// endpoint.expectedMessageCount(1);
		endpoint.message(0).body().isInstanceOf(PurchaseOrder.class);

		PurchaseOrder order = new PurchaseOrder();
		order.setName("Camel in action");
		order.setPrice(4995);
		order.setAmount(1);
		template.sendBody("direct:javaOrder", order);
		// Must sleep to wait all the route routed. else the test will fail
		Thread.sleep(2000);
		assertMockEndpointsSatisfied();
	}

}
